//
//  UISearchBar+TKIM.m
//  TKIM
//
//  Created by liupm on 15/10/31.
//  Copyright © 2015年 liupm. All rights reserved.
//

#import "TKIMSearchBar.h"

@implementation TKIMSearchBar
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _isShowBottomLine = YES;
        _bottomLineColor = [TKIMColorHelper stringToColor:@"#E5E5E5"];
    }
    return self;
}


-(void)setTextFieldBackgroudColor:(UIColor *)textFieldBackgroudColor
{
    CGFloat systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (systemVersion >= 13.0) { // 适配iOS13
        
        [self setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:243/255.0 alpha:1.0]] forBarPosition:(UIBarPositionAny) barMetrics:(UIBarMetricsDefault)];
        
        UITextField *textField = self.searchTextField;
        [textField setBorderStyle:UITextBorderStyleNone];
        textField.background = nil;
        textField.frame = CGRectMake(8, 8, self.bounds.size.width - 2* 8,
                                     self.bounds.size.height - 2* 8);
        textField.layer.cornerRadius = 5;
        textField.clipsToBounds = YES;
        textField.backgroundColor =textFieldBackgroudColor;
        
    }else{ // iOS13以下
        
        UIView *view = (UIView *)self.subviews.lastObject;
            for (UIView *subView in view.subviews)
            {
                if ([subView isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
                    [subView removeFromSuperview];
                }
                if ([subView isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                    UITextField *textField = (UITextField *)subView;
                    [textField setBorderStyle:UITextBorderStyleNone];
                    textField.background = nil;
                    textField.frame = CGRectMake(8, 8, self.bounds.size.width - 2* 8,
                                                 self.bounds.size.height - 2* 8);
                    textField.layer.cornerRadius = 5;
                    textField.clipsToBounds = YES;
                    textField.backgroundColor =textFieldBackgroudColor;
                }
            }
    }
}

- (UIImage *)imageWithColor: (UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    if (_isShowBottomLine)
    {
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, rect.size.height-1,rect.size.width, 1)];
        lineView.backgroundColor = [UIColor whiteColor];
        UIView *line =  [[UIView alloc]initWithFrame:CGRectMake(0, 0,rect.size.width, 0.5)];
        line.backgroundColor =  _bottomLineColor;
        [lineView addSubview:line];
        [self addSubview:lineView];
    }
}


/**
 *  自定义控件自带的取消按钮的文字（默认为“取消”/“Cancel”）
 *
 *  @param title 自定义文字
 */
- (void)setCancelReturnKeyType:(UIReturnKeyType )type
{
    // Set Search Button Title to Done
    for (UIView *searchBarSubview in [self subviews]) {
        if ([searchBarSubview conformsToProtocol:@protocol(UITextInputTraits)]) {
            // Before iOS 7.0
            @try {
                [(UITextField *)searchBarSubview setReturnKeyType:UIReturnKeyDone];
                //[(UITextField *)searchBarSubview setKeyboardAppearance:UIKeyboardAppearanceAlert];
            }
            @catch (NSException * e) {
                // ignore exception
            }
        } else {
            // iOS 7.0
            for(UIView *subSubView in [searchBarSubview subviews]) {
                if([subSubView conformsToProtocol:@protocol(UITextInputTraits)]) {
                    @try {
                        [(UITextField *)subSubView setReturnKeyType:UIReturnKeyDone];
                        //[(UITextField *)searchBarSubview setKeyboardAppearance:UIKeyboardAppearanceAlert];
                    }
                    @catch (NSException * e) {
                        // ignore exception
                    }
                }
            }
        }
    }
}


/**
 *  @Author lpm, 15-12-07 17:12:01
 *
 *  @brief  失去焦点
 *
 *  @return
 */
-(BOOL)resignFirstResponder
{
   BOOL r = [super resignFirstResponder];
    NSArray *arr = self.subviews;
    
    if (arr.count == 1)
    {
        UIView *view = arr[0];
        for(UIView *control in view.subviews)
        {
            if ([control isKindOfClass:[UIButton class]])
            {
                UIButton * btn =(UIButton *)control;
                [btn setTitle:@"取消" forState:UIControlStateNormal ];
                btn.enabled=YES;
                [btn addTarget:self action:@selector(doAction) forControlEvents:UIControlEventTouchUpInside];
            }
        }
    }
    else
    {
        for(UIView *control in arr)
        {
            if ([control isKindOfClass:[UIButton class]])
            {
                UIButton * btn =(UIButton *)control;
                [btn setTitle:@"取消" forState:UIControlStateNormal ];
                btn.enabled=YES;
                [btn addTarget:self action:@selector(doAction) forControlEvents:UIControlEventTouchUpInside];
            }
        }
    }
    return r;
}



/**
 *  @Author lpm, 15-12-07 17:12:34
 *
 *  @brief  取消事件
 */
-(void)doAction
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(searchBarCancelButtonClicked:)])
    {
        [self.delegate searchBarCancelButtonClicked:self];
    }
}



@end
